<template>
  <div class="my_network_box">
    <div class="add_btn_top">
      <div v-if="!isTopBtn" class="sw_btn_box">
        <div
          :style="{
            color: switchText == '显示筛选' ? '#666666' : '#409EFF',
            fontSize: '14px',
          }"
        >
          {{ switchText }}
        </div>
        <el-switch
          v-permission="[4, 'switch']"
          style="margin-left: 10px"
          active-color="#2680D2"
          v-model="screen"
        >
        </el-switch>
        <div class="line"></div>
      </div>
      <div>
        <el-button
          v-permission="[1, 'button']"
          @click="handAdd"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          >添加</el-button
        >
      </div>
      <!-- <div>
        <el-button
          @click="handAdd222"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          >测试跨域token接口</el-button
        >
      </div> -->
      <div style="margin-left: 10px" v-if="isDelbtn" v-permission="2">
        <el-button @click="handDel(ids)" icon="el-icon-delete" size="mini"
          >删除</el-button
        >
      </div>
    </div>
    <div class="gateway">
      <div class="user_admin_tree" v-init-screen-h="10">
        <div class="flex-x" style="margin-bottom: 10px">
          <el-input
            class="treeInput"
            placeholder="请输入"
            suffix-icon="el-icon-search"
            v-model="filterText"
            size="mini"
          >
          </el-input>
          <el-button
            type="primary"
            size="mini"
            @click="resetChecked"
            style="margin-left: 6px"
            >重置</el-button
          >
        </div>
        <div class="all_open">
          <div class="open_box" @click="unFoldAll2(treedata)">
            <img class="icon" src="@/assets/treeicon1.png" />
            <span class="expandAll text_nowrap">全部展开</span>
          </div>
          <div class="verticalLine"></div>
          <div class="open_box" @click="collapseAll2(treedata)">
            <img class="icon" src="@/assets/treeicon2.png" />
            <span class="closeAll text_nowrap">全部收起</span>
          </div>
        </div>
        <el-tree
          @check="treeCheck"
          show-checkbox
          :data="treedata"
          :props="defaultProps"
          default-expand-all
          accordion
          :filter-node-method="filterNode"
          highlight-current
          ref="tree"
          node-key="id"
        >
        </el-tree>
      </div>
      <div
        v-permission="[4, 'list']"
        :style="{
          width: screen ? '62%' : '80%',
          background: '#fff',
        }"
      >
        <el-table
          height="100px"
          v-adaptive
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            :selectable="selectEnable"
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column label="序号" prop="id" align="left" width="50">
          </el-table-column>
          <el-table-column
            label="用户名"
            prop="username"
            align="left"
            width="100"
          >
          </el-table-column>
          <el-table-column label="手机号" prop="phone" align="left" width="120">
          </el-table-column>
          <el-table-column label="部门信息" prop="deptName" align="left">
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.deptName"
                size="small"
                class="tag_width"
                >{{ scope.row.deptName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="角色信息" prop="roleNames" align="left">
            <template slot-scope="scope">
              <div v-if="roleNames(scope.row.roleNames)">
                <el-tag
                  v-for="(item, index) in roleNames(scope.row.roleNames)"
                  :key="index"
                  class="tag_role_name_item"
                  size="small"
                  >{{ item }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="sex" align="left" width="44">
            <template slot-scope="scope">
              <span v-if="scope.row.sex == 2"> 女 </span>
              <span v-if="scope.row.sex == 1"> 男 </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" align="left">
          </el-table-column>

          <el-table-column label="操作" width="120" align="center">
            <template
              slot-scope="scope"
              v-if="scope.row.username !== 'super_admin'"
            >
              <el-tooltip
                class="item"
                effect="light"
                content="分配角色"
                placement="top-start"
              >
                <span
                  style="color: #2680d2; font-size: 16px; margin-right: 10px"
                  class="el-icon-user-solid"
                  @click="handDis(scope.row)"
                ></span>
              </el-tooltip>

              <span
                style="color: #2680d2; font-size: 16px; margin-right: 10px"
                class="el-icon-edit-outline"
                @click="handEdit(scope.row.id)"
              ></span>
              <span
                v-permission="[2, 'icon']"
                style="color: #2680d2; font-size: 16px; margin-right: 10px"
                class="el-icon-delete"
                @click="handDel(scope.row.id)"
              ></span>
              <el-tooltip
                class="item"
                effect="light"
                content="重置密码"
                placement="top-start"
              >
                <span
                  v-permission="[6, 'icon']"
                  style="color: #2680d2; font-size: 16px"
                  class="el-icon-unlock"
                  @click="handEditPaw(scope.row.id)"
                ></span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          @pagination="pagination"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          :pageSizes.sync="pageSizes"
        />
      </div>
      <div v-if="screen" class="searchForm">
        <div style="width: 100%" v-init-screen-h>
          <div class="select">筛选</div>
          <div class="">
            <div class="searchText">用户名</div>
            <el-input
              class="inputStyle"
              v-model="form.username"
              clearable
              size="mini"
              placeholder="请输入用户名"
            >
            </el-input>
          </div>
          <div class="">
            <div class="searchText">手机号</div>
            <el-input
              class="inputStyle"
              v-model="form.phone"
              size="mini"
              placeholder="请输入手机号"
            >
            </el-input>
          </div>
        </div>
        <div class="bottomBtn">
          <el-button class="reset" size="mini" style="width: 50%" @click="reSet"
            >重置</el-button
          >
          <el-button
            @click="init"
            class="submit"
            size="mini"
            style="width: 50%"
            type="primary"
            >提交</el-button
          >
        </div>
      </div>
    </div>

    <AddDialog
      ref="addDialgRef"
      @closeDialog="closeDialog"
      :isedit="isedit"
      :showDialog.sync="showDialog"
    ></AddDialog>
    <!-- 分配 -->
    <distributionDialog
      ref="distributionDialogRef"
      @closeDialog="closeDialog"
      :id="id"
      :showDialog.sync="showDisDialog"
    ></distributionDialog>
    <EditPaw
      @closeDialog="closeDialog"
      :userId="id"
      :showDialog.sync="showEditPawDialog"
    ></EditPaw>
  </div>
</template>

<script>
import "@/assets/style/deviceCss/filterWindow.css";
import Pagination from "@/views/common/page";
import EditPaw from "./EditPaw.vue";
import { getAuthToken } from "@/api/userAuth";
import {
  getUserInfoList,
  delUser,
  getUserDetails,
  useAssignedRoles,
  useRoles,
} from "@/api/userAuth";
import { paginationMixins } from "@/mixin/pagination";
import AddDialog from "./AddDialog.vue";
import distributionDialog from "./distributionDialog.vue";
import _ from "lodash";
import { paramsValidate } from "@/utils/utils";
import { getDeptList } from "@/api/department";
import Qs from "qs";
export default {
  mixins: [paginationMixins],
  components: {
    Pagination,
    AddDialog,
    distributionDialog,
    EditPaw,
  },
  props: {
    isShowScreen: {
      type: Boolean,
      default: false,
    },
    isTopBtn: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      filterText: "",
      showEditPawDialog: false,
      showDisDialog: false,
      showDialog: false,
      screen: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      addFlag: false,
      tableData: [],
      isedit: false,
      disParams: {},
      defaultProps: {
        children: "children",
        label: "name",
      },
      treedata: [],
      form: {
        username: "",
        phone: "",
      },
      id: "",
      deptIds: "",
      ids: "", //用于多选删除
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    isDelbtn() {
      return this.ids;
    },
    roleNames() {
      return function (item) {
        if (item) {
          return item.split(",");
        } else {
          return "";
        }
      };
    },
  },
  mounted() {
    this.getTreedata();
    // this.getAssettypes();
  },
  methods: {
    setAllExpand(arr, isExpand) {
      let self = this;
      arr.forEach((el) => {
        self.$refs.tree.store.nodesMap[el.id].expanded = isExpand;
        if (el.children) {
          self.setAllExpand(el.children, isExpand);
        }
      });
    },
    // 树全部展开
    unFoldAll2(data) {
      this.setAllExpand(data, true);
    },
    // 全部折叠
    collapseAll2(data) {
      this.setAllExpand(data, false);
    },
    // getTreeId(data, ids, name) {
    //   data.forEach((item) => {
    //     if (item.name.indexOf(name) !== -1) {
    //       ids.push(item.id);
    //     } else {
    //       if (item.children) {
    //         this.getTreeId(item.children, ids, name);
    //       }
    //     }
    //   });
    // },

    getTreedata() {
      getDeptList({ name: this.name }).then((res) => {
        const { data } = res.data;
        this.treedata = data;
      });
    },
    handEditPaw(id) {
      this.id = id;
      this.showEditPawDialog = true;
    },
    selectEnable(row, index) {
      if (row.username !== "super_admin") {
        return true;
      } else {
        return false;
      }
    },
    chooseNode(value, data, node) {
      if (data.name.indexOf(value) !== -1) {
        return true;
      }
      const level = node.level;
      // 如果传入的节点本身就是一级节点就不用校验了
      if (level === 1) {
        return false;
      }
      // 先取当前节点的父节点
      let parentData = node.parent;
      // 遍历当前节点的父节点
      let index = 0;
      while (index < level - 1) {
        // 如果匹配到直接返回，此处name值是中文字符，enName是英文字符。判断匹配中英文过滤
        if (parentData.data.name.indexOf(value) !== -1) {
          return true;
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent;
        index++;
      }
      // 没匹配到返回false
      return false;
    },
    treeCheck(data, node) {
      const { checkedKeys } = node;
      console.log("object :>> ", node, checkedKeys);
      if (checkedKeys.length) {
        this.deptIds = checkedKeys.join(",");
      } else {
        this.deptIds = "";
      }
      this.init();
    },
    // 树列表查询事件
    filterNode(value, data, node) {
      if (!value) {
        //如果数据为空，则返回true,显示所有的数据项
        node.expanded = false;
        return true;
      } // 查询列表是否有匹配数据，将值小写，匹配英文数据
      let val = value.toLowerCase();
      return this.chooseNode(val, data, node);

      // if (!value) return true;

      // return data.name.indexOf(value) !== -1;
    },
    // 多选
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id).join(",");
    },
    // 打开分配
    async handDis(row) {
      this.id = row.id;
      this.showDisDialog = true;
    },
    // 重置
    reSet() {
      for (const key in this.form) {
        this.form[key] = "";
      }
      this.init();
    },
    async handEdit(userId) {
      this.showDialog = true;
      this.$nextTick(async () => {
        this.isedit = true;
        this.$refs.addDialgRef.form.url = "";
        const res = await getUserDetails({ userId });
        res.data.data.user.password = "********";
        res.data.data.user.deptId = res.data.data.deptId;
        // res.data.data.user.tenantIds = res.data.data.deptId;
        res.data.data.user.url = res.data.data.user.url
          ? res.data.data.user.url
          : "/iot/user/default_user.png";

        res.data.data.user.tenantIds =
          res.data.data.tenantList &&
          res.data.data.tenantList.map((item) => item.id).join(",");
        res.data.data.user.tenantCloneIds =
          res.data.data.tenantList &&
          res.data.data.tenantList.map((item) => item.id);
        this.$refs.addDialgRef.form = res.data.data.user;
        console.log("res :>> ", this.$refs.addDialgRef.form);
      });
    },
    handDel(id) {
      // 如果是自己删除自己 退出登录
      if (id == this.$store.state.user.user.userId) {
        this.$confirm("删除自己将会退出登录,是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          await delUser(id);
          this.$msg({
            type: "success",
            message: "删除成功!",
          });
          await this.$store.dispatch("user/logout");
          this.$router.push("/login");
          // this.init();

          // that.getStatusToken();
        });
      } else {
        this.$confirm("是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          await delUser(id);
          this.$msg({
            type: "success",
            message: "删除成功!",
          });
          this.init();
          // that.getStatusToken();
        });
      }
    },
    async handAdd222() {
      await getAuthToken(
        Qs.stringify({
          grant_type: "password",
          username: "super_admin",
          password: "super_admin",
          tenantId: 1,
        })
      );
    },
    handAdd() {
      this.isedit = false;
      this.showDialog = true;
      this.$nextTick(() => {
        this.$refs.addDialgRef.form.url = "/iot/user/default_user.png";
      });
    },

    closeDialog(isRefresh) {
      // isRefresh是否刷新
      if (isRefresh) {
        this.init();
      }
    },
    closeDisDialog(isRefresh) {
      // isRefresh是否刷新
      if (isRefresh) {
        this.init();
      }
    },
    //分页回调
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.init();
    },
    resetChecked() {
      // this.setAllExpand(this.treedata, true);
      this.filterText = "";
      this.$refs.tree.setCheckedKeys([]);
      this.deptIds = "";

      this.init();
    },
    async init(token) {
      const res = await getUserInfoList(
        {
          page: this.pageNum,
          pageSize: this.pageSize,
          ...this.form,
        },
        this.deptIds ? this.deptIds : ""
      );
      // this.screen = false;
      if (paramsValidate(this.form)) {
        this.switchText = "显示筛选";
      } else {
        this.switchText = "显示筛选(已筛选)";
      }
      const { data } = res.data;
      this.total = data.total;
      this.tableData = data.list;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.all_open {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  margin: 16px 0;
  font-size: 12px;
  color: #666;
  .open_box {
    align-items: center;
    display: flex;
    cursor: pointer;
    .icon {
      margin-right: 6px;
    }
  }
}
.user_admin_tree {
  width: 20%;
  margin-right: 14px;
  padding: 10px;
  background-color: #fff;
}
.tag_role_name_item {
  margin-right: 6px;
  margin-bottom: 2px;
  &:last-child {
    margin-right: 0;
  }
}
.filter_data {
  z-index: 99;
  margin-left: 14px;
  width: 25%;
  background-color: rgb(255, 255, 255);
  display: flex;
  flex-direction: column;
  position: relative;
}
.gateway {
  display: flex;
  justify-content: space-between;
  width: 100%;
  /* margin-bottom: 20px; */
}
.leftColumn {
  float: left;
}
.topBtn {
  position: absolute;
  right: 5.8%;
  top: -30px;
}
.rightColumn {
  /* margin-left: 30px; */
  width: 23%;
  background-color: #fff;
  overflow-x: hidden;
}
.switch-text {
  float: left;
  margin-top: -6px;
  margin-right: 8px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 22px;
}
.screenSwitch {
  float: left;
  margin-top: -5px;
}
.line {
  float: left;
  display: inline-block;
  height: 12px;
  width: 1px;
  vertical-align: middle;
  background-color: #999;
  margin: -1px 17px 0 15px;
}

.tab_height {
}
.my_network_box /deep/ .el-table {
  .el-tag {
    white-space: normal;
    height: auto;
    line-height: 16px;
  }
  /* overflow: auto; */
}
.my_network_box /deep/ .el-table__row {
  td:not(.is-hidden):last-child {
    /* bottom: -1px; */
    right: -1px;
  }
}
.my_network_box /deep/ .el-table__header {
  th:not(.is-hidden):last-child {
    right: -1px;
  }
}
.my_network_box /deep/ .el-table__header {
  th:not(.is-hidden):first-child {
    bottom: 1px;
  }
}
.my_network_box /deep/ .el-table__header .is-leaf {
  bottom: 1px;
}
.my_network_box {
  position: relative;
  .sw_btn_box {
    display: flex;
    align-items: center;
  }
  /deep/ .el-form-item__label {
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #999999;
  }
}
</style>
